#!/usr/bin/env python3
"""
环境验证脚本

用于验证虚拟环境是否正确配置，所有依赖是否正常安装。
"""

import sys
import os
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"Python版本: {version.major}.{version.minor}.{version.micro}")

    if version.major == 3 and version.minor >= 8:
        print("✅ Python版本符合要求 (>= 3.8)")
        return True
    else:
        print("❌ Python版本过低，需要3.8或更高版本")
        return False

def check_virtual_env():
    """检查是否在虚拟环境中"""
    if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
        print("✅ 正在使用虚拟环境")
        print(f"   虚拟环境路径: {sys.prefix}")
        return True
    else:
        print("❌ 未检测到虚拟环境")
        return False

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'requests',
        'bs4',  # beautifulsoup4的实际导入名
        'selenium',
        'lxml',
        'yaml',  # pyyaml的实际导入名
        'dateutil',  # python-dateutil的实际导入名
        'colorlog'
    ]

    missing_packages = []

    for package in required_packages:
        try:
            __import__(package)
            print(f"✅ {package}")
        except ImportError:
            print(f"❌ {package} - 未安装")
            missing_packages.append(package)

    if missing_packages:
        print(f"\n缺少的包: {', '.join(missing_packages)}")
        print("请运行: pip install -r requirements.txt")
        return False
    else:
        print("\n✅ 所有依赖包已安装")
        return True

def check_project_structure():
    """检查项目结构"""
    required_dirs = [
        'src',
        'config',
        'output',
        'logs'
    ]

    required_files = [
        'requirements.txt',
        'config/urls.yaml',
        'config/settings.py',
        'src/main.py'
    ]

    missing_items = []

    print("\n检查项目结构:")

    for dir_name in required_dirs:
        if Path(dir_name).exists():
            print(f"✅ 目录: {dir_name}")
        else:
            print(f"❌ 目录: {dir_name} - 不存在")
            missing_items.append(dir_name)

    for file_name in required_files:
        if Path(file_name).exists():
            print(f"✅ 文件: {file_name}")
        else:
            print(f"❌ 文件: {file_name} - 不存在")
            missing_items.append(file_name)

    if missing_items:
        print(f"\n缺少的项目: {', '.join(missing_items)}")
        return False
    else:
        print("\n✅ 项目结构完整")
        return True

def check_imports():
    """检查模块导入"""
    print("\n检查模块导入:")

    try:
        # 添加项目根目录到Python路径
        project_root = Path(__file__).parent
        sys.path.insert(0, str(project_root))

        # 测试导入
        from src.models.data_model import ScrapedData
        print("✅ 数据模型导入成功")

        from src.utils.logger import get_logger
        print("✅ 日志工具导入成功")

        from src.utils.text_processor import text_processor
        print("✅ 文本处理器导入成功")

        from src.utils.markdown_writer import markdown_writer
        print("✅ Markdown写入器导入成功")

        from src.config_loader import config_loader
        print("✅ 配置加载器导入成功")

        from src.scraper.scraper_factory import ScraperFactory
        print("✅ 爬虫工厂导入成功")

        return True

    except ImportError as e:
        print(f"❌ 模块导入失败: {e}")
        return False

def main():
    """主函数"""
    print("=" * 50)
    print("环境验证检查")
    print("=" * 50)

    checks = [
        ("Python版本", check_python_version),
        ("虚拟环境", check_virtual_env),
        ("依赖包", check_dependencies),
        ("项目结构", check_project_structure),
        ("模块导入", check_imports)
    ]

    results = []

    for name, check_func in checks:
        print(f"\n{'-' * 20} {name} {'-' * 20}")
        result = check_func()
        results.append((name, result))

    print("\n" + "=" * 50)
    print("验证结果总结")
    print("=" * 50)

    passed = 0
    total = len(results)

    for name, result in results:
        status = "✅ 通过" if result else "❌ 失败"
        print(f"{name}: {status}")
        if result:
            passed += 1

    print(f"\n总体结果: {passed}/{total} 项检查通过")

    if passed == total:
        print("🎉 环境配置完全正确！")
        print("\n您可以运行以下命令:")
        print("  python test_basic.py          # 运行基础测试")
        print("  python src/main.py --list     # 列出配置的网站")
        print("  python src/main.py --test     # 测试配置")
        print("  python src/main.py            # 运行爬虫")
        return 0
    else:
        print("⚠️  环境配置存在问题，请根据上述错误信息进行修复")
        return 1

if __name__ == "__main__":
    sys.exit(main())
